<!DOCTYPE html>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
<html>
<head>
	<meta charset="UTF-8">
	<script src="../script/jquery.min.js"></script>
	<link rel="stylesheet" href="../script/semantic/semantic.min.css">
	<script type='text/javascript' src="../script/semantic/semantic.min.js"></script>
	<script type='text/javascript' src="../script/ao_module.js"></script>
	<style>
	body, html {
		height: 100%;
		margin: 0;
		background-color:#2b2b2b;
	}

	#settingMenu .ui.toggle.checkbox input:checked ~ .box,#settingMenu  .ui.toggle.checkbox input:checked ~ label{
		color: rgb(189, 189, 189) !important;
	}
	</style>
	<script>
		//Scrolling Controller
		var keys = {37: 1, 38: 1, 39: 1, 40: 1};

		function preventDefault(e) {
		e = e || window.event;
		if (e.preventDefault)
			e.preventDefault();
		e.returnValue = false;  
		}

		function preventDefaultForScrollKeys(e) {
			if (keys[e.keyCode]) {
				preventDefault(e);
				return false;
			}
		}

		function disableScroll() {
		if (window.addEventListener) // older FF
			window.addEventListener('DOMMouseScroll', preventDefault, false);
			window.onwheel = preventDefault; // modern standard
			window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
			window.ontouchmove  = preventDefault; // mobile
			document.onkeydown  = preventDefaultForScrollKeys;
		}

		function enableScroll() {
			if (window.removeEventListener)
				window.removeEventListener('DOMMouseScroll', preventDefault, false);
				window.onmousewheel = document.onmousewheel = null; 
				window.onwheel = null; 
				window.ontouchmove = null;  
				document.onkeydown = null;  
			}
		disableScroll();
	</script>
</head>
<body>
<div id="loading" style="position: fixed;top: 0;left: 0;background:rgba(0,0,0,0.5);color:white;width:100%;height:100%;z-index:100">
	<div class="ui active dimmer">
        <div class="ui text loader">Loading</div>
    </div>
</div>
<div class="ui attached inverted message" style="margin-top: 0em;" onClick="ToggleChapters();">
    <div class="header"><i class="bookmark icon"></i>You are already reached the top of this manga.</div>
    <p>Click here to select more chapters.</p>
</div>

<div id="MangaList" class="ui list">
	<div class="item" style="width: 100%;display: flex;align-items: flex-start;"><img src="" style="width: 100%;height: auto;"></img></div>
</div>

<!-- Click Detect DIV -->
<div id="clickInterface" style="opacity:0;
    filter: alpha(opacity = 0);
    position:fixed;
    top:25%; bottom:25%; left:0; right:0;
	width:100%;
	height:50%;
    display:block;
    z-index:998;
    background:transparent;" onClick="">
</div>

<!-- Setting Config DIV -->
<div id="SettingInterface" style="
    position:fixed;
    top:0; bottom:0; left:0; right:0;
	width:100%;
	height:100%;
    display:block;
    z-index:1501;
	display:none;" onClick="">
	<div id="settingMenu" class="ui very narrow container" style="top:15%;z-index:1502;">
		<div class="ui container" style="color:white;">
		<div class="ui inverted segment" style="background:rgba(61,61,61,0.8);">
			<p style="font-size:120%;"><i class='setting icon'></i>Settings</p>
			<div class="ui toggle checkbox">
				<input type="checkbox" id="lefthand">
				<label for="lefthand" style="color:white;"><i class="hand paper icon" style="transform: scaleX(-1);-moz-transform: scaleX(-1);-webkit-transform: scaleX(-1);-ms-transform: scaleX(-1);"></i>Left hand mode <br> Click the left section of the view for downward auto scrolling instead of right section.</label>
			</div><br><br>
			<div class="ui toggle checkbox">
				<input type="checkbox" id="progress">
				<label for="progress" style="color:white;"><i class="save icon"></i>Save progress <br> Save the current progress and return to that page automatically in the future.</label>
			</div><br><br>
			<div class="ui toggle checkbox">
				<input type="checkbox" id="pcm">
				<label for="pcm" style="color:white;"><i class="save icon"></i>PC Mode <br> Scale down the manga a bit to make you feel better on a big PC screen.</label>
			</div>
		</div>
		</div>
	</div>
</div>

<!-- Page Info DIV-->
<div align="right" style="position: fixed;bottom: 0;right: 0;background:rgba(0,0,0,0.5);color:white;z-index:1000;">
<div id="PageInfo" class="ui fluid text container">
Loading Page Data...
</div>
</div>
<!-- Next Chapter Message-->
<div class="ui inverted message" onclick="NextChapter();" style="cursor: pointer;">
    <div class="header"><i class="bookmark icon"></i>You have finished this chapter.</div>
    <p id="reminder">Click this box to proceed to next chapter.</p>
</div>

<!-- Start of Chapter Selector-->
<div id="ChapterSelector" class="ui inverted message" style="color:white;display:none;">
<div class="ui stackable grid" id="chapterlist">
    
</div>
</div>
<!-- END of Chapter Selector-->
<div align="center" style="width:100%">
<div class="ui buttons" >
    <button class="ui inverted basic button" onClick="window.location.href='index.html'" style="color:white !important;"><i class="chevron left icon"></i>Back</button>
    <button class="ui inverted basic button" onClick="ToggleChapters();" style="color:white !important;"><i class="book icon"></i>Chapters</button>
</div>
</div>

<br>
<br>
<script type="text/javascript">
    var pages = [];
	var titles = "";
	var chapterPaths = [];
	var nextChapterID = 0;
	var maxChapterID = 0;
	var pagesNum = pages.length; //This page number is the number of files in the directory, not the actual page number
	var positions = [];
	var currentPage = 0;
	var chapterShown = false;
	var lastpage = 0;
	var floatWindow = !(!parent.isFunctionBar); //Updated support on floatWindow System
	//Auto save and left hand mode
	var autoSave = false;
	var leftHandMode = false;
	var isMobile = false; //initiate as false
	// device detection
	if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
		|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
		isMobile = true;
	}
	var preRenderComplete = false;
	var pcm = false; //PC Mode
	//Screen Width and height data
	var screenWidth = $(window).width();
	var screenHeight = $(window).height();
	//Debug Interface
	console.log("This Chapter ID: ",nextChapterID);
	console.log("Max Chapter ID: ",maxChapterID);
	console.log("Chapter Paths: ",chapterPaths);

	if(floatWindow){
		$("#PageInfo").parent().css("bottom","0px");
		$("body").css("padding-bottom","20px");
	}

	//Load the content of this manga chapter
	var mangaFolder = window.location.hash.substr(1);
	ao_module_agirun("Manga/backend/getMangaInfo.js", {folder: mangaFolder}, function(data){
		console.log(data);
		pages = data.pages;
		titles = data.title,
		chapterPaths = data.otherChapterDir;
		nextChapterID = 0;
		maxChapterID = chapterPaths.length;

		//Render manga to ui
		$("#MangaList").html("");
		data.pages.forEach(page => {
			$("#MangaList").append(`<div class="item" style="width: 100%;display: flex;align-items: flex-start;"><img src="../media?file=${page}" style="width: 100%;height: auto;"></img></div>`)
		});

		//Render next chapter button
		$("#chapterlist").html("");
		var counter = 0;
		var nextOneIsPreRender = false;
		var prerender = "";
		data.otherChapterDir.forEach(chapter => {
			var chapterName = chapter.split("/").pop();
			var chapterWide = "four";
			if (isMobile){
				chapterWide = "sixteen";
			}
			if (chapterName == data.title[1]){
				$("#chapterlist").append(`<div class="${chapterWide} wide column compact" style="color:white; padding: 0.3em !important;"><a class="ui fluid inverted basic disabled button" style="color:white;">${chapterName}</a></div>`);
				nextChapterID = counter;
				nextOneIsPreRender = true;
			}else{
				if (nextOneIsPreRender){
					nextOneIsPreRender = false;
					prerender = chapter;
				}
				$("#chapterlist").append(`<div class="${chapterWide} wide column compact" style="color:white; padding: 0.3em !important;"><a class="ui fluid inverted basic button" style="color:white;" onClick="ChapterRedirect('${chapter}');">${chapterName}</a></div>`);
			}
			counter++;
		});

		//Start waiting for all images to load
		var imagesLoaded = 0;
		var totalImages = $('img').length;
		$('img').on('load', function(event) {
			imagesLoaded++;
			if (imagesLoaded == totalImages) {
				init();

				if (nextOneIsPreRender == true){
					//There is no next chapter
					preRenderComplete = true;
				}else{
					//Start next chapter pre-render
					ao_module_agirun("Manga/backend/getMangaInfo.js",{folder: prerender}, function(data){
						//Pre-render complete
						console.log("Next chapter pre-render completed")
						preRenderComplete = true;
					});
				}
			
			}
		});
		
	});
	
	//Window onload replace document.ready due to the measurement of each div have to be done after the page loaded
	function init(){
		$('#loading').hide(); 
		enableScroll();
		positions = [];
		var count = 0;
		$('.item').each(function(i, obj) {
			var offsets = $(this).offset();
			var top = offsets.top;
			//console.log(top);
			positions.push(top);
			count += 1;
		});
		if (nextChapterID + 1 > maxChapterID - 1){
				$('#reminder').html('There is no more chapters.');
		}
		//alert(count);
		//Check if PCB Mode
		if (localStorage.pcm !== null){
			pcm = (localStorage.pcm == 'true');
			console.log('PC Mode: ' + pcm);
			$('#pcm').prop("checked",pcm);
		}
		if (pcm){
			//If PC mode is enabled, re-allign all image
			setTimeout(function(){ PCMode(0); }, 100);
		}
		//AutoSave Function
		if (localStorage.autoSave !== null){
			autoSave = (localStorage.autoSave == 'true');
			console.log('AutoSave: ' + autoSave);
			$('#progress').prop("checked",autoSave);
			if (localStorage.getItem(titles[0] + "-" + titles[1]) !== null && autoSave){
				var page = localStorage.getItem(titles[0] + "-" + titles[1]);
				console.log('Loading progress: ' + page);
				if (page != count){
					//Not yet finished
					console.log(count,page)
					setTimeout(function(){ GoToPage(page); },100);
				}
			}
		}
		if(localStorage.getItem(titles[0] + "-" + titles[1]) !== null && (localStorage.autoSave === null || localStorage.autoSave == 'false')){
				localStorage.removeItem(titles[0] + "-" + titles[1]);
				console.log("Old autosave record removed.");
			}
			
		//Left hand Mode function
		if (localStorage.leftHandMode !== null){
			leftHandMode = (localStorage.leftHandMode == 'true');
			console.log('Left Hand Mode: ' + leftHandMode);
			$('#lefthand').prop("checked",leftHandMode);
		}
		
		UpdatePageInfo();
	}
	
	//Check if settings changed
	$('#lefthand').change(function(){
	  if($(this).is(':checked')){
		localStorage.leftHandMode = true;
		leftHandMode = true;
		console.log('Left Hand Mode Changed to ' + leftHandMode);
	  } else {
		localStorage.leftHandMode = false;
		leftHandMode = false;
		console.log('Left Hand Mode Changed to ' + leftHandMode);
	  }
	});

	$('#progress').change(function(){
	  if($(this).is(':checked')){
		localStorage.autoSave = true;
		autoSave = true;
		console.log('Auto Save Changed to ' + autoSave);
		localStorage.setItem(titles[0] + "-" + titles[1], currentPage);
	  } else {
		localStorage.autoSave = false;
		autoSave = false;
		console.log('Auto Save Changed to ' + autoSave);
	  }
	});
	
	$('#pcm').change(function(){
	  if($(this).is(':checked')){
		localStorage.pcm = true;
		pcm = true;
		console.log('PC Mode Changed to ' + pcm);
		PCMode();
	  } else {
		localStorage.pcm = false;
		pcm = false;
		console.log('PC Mode Changed to ' + pcm);
		MobileMode();
	  }
	});
	//End of setting change section
	
	//Recalculate page number accodring to new image position
	window.onresize = function() {
		positions = [];
		$('.item').each(function(i, obj) {
			var offsets = $(this).offset();
			var top = offsets.top;
			//console.log(top);
			positions.push(top);
			if (nextChapterID + 1 > maxChapterID - 1){
				$('#reminder').html('There is no more chapters.');
			}
			screenWidth = $(window).width();
			screenHeight = $(window).height();
		});
	}
	
	//Click Page Scroll functions
	var ControlPanel = document.getElementById('clickInterface');
	ControlPanel.addEventListener("click", AutoPageScroll, false);
	
	function AutoPageScroll(e){
		var clickX = e.clientX;
		var clickY = e.clientY;
		var split = screenWidth / 2;
		if (leftHandMode == true){
			//Left side is next page, right side is previous page
			if (clickX < split){
				//left
				scrollDown();
			}else{
				//right
				scrollUp();
			}
		}else{
			if (clickX > split){
				//right
				scrollDown();
			}else{
				//left
				scrollUp();
			}
		}
	}
	
	function scrollDown(){
		$("html, body").animate({ scrollTop: $(window).scrollTop() + screenHeight * 0.8 }, 1000);
	}
	function scrollUp(){
		$("html, body").animate({ scrollTop: $(window).scrollTop() - screenHeight * 0.8 }, 1000);
	}
	//End of auto scrolling
	
	//Resize all image to PC mode
	function PCMode(mode){
		var tmpPage = currentPage;
		$('.item').each(function(i, obj) {
			$(this).css("width","50%");
		});
		$('#MangaList').css("width","100%");
		$('#MangaList').prop("align","center");
		setTimeout(function(){ CalculatePageOffsets(); }, 1000);
		if (mode != 0){
			setTimeout(function(){ GoToPage(tmpPage); }, 100);
		}
	}
	function MobileMode(){
		var tmpPage = currentPage;
		$('.item').each(function(i, obj) {
			$(this).css("width","100%");
		});
		$('#MangaList').css("width","");
		$('#MangaList').prop("align","");
		setTimeout(function(){ CalculatePageOffsets(); }, 1000);
		setTimeout(function(){ GoToPage(tmpPage); }, 100);
	}
	function CalculatePageOffsets(){
		console.log('Calculating Page Offsets');
		positions = [];
		$('.item').each(function(i, obj) {
			var offsets = $(this).offset();
			var top = offsets.top;
			//console.log(top);
			positions.push(top);
			if (nextChapterID + 1 > maxChapterID - 1){
				$('#reminder').html('There is no more chapters.');
			}
		});
		UpdatePageInfo();
		 
	}
	//Update page info on window scroll
	$( window ).scroll(function() {
	  //console.log($(window).scrollTop());
	  currentPage = getPageNum($(window).scrollTop(),positions);
	  
	  if (autoSave == true && currentPage != 0 && lastpage != currentPage){
		  //Save Page number as: "title-chapter:page"
		  localStorage.setItem(titles[0] + "-" + titles[1], currentPage);
		  lastpage = currentPage;
		  console.log(localStorage.getItem(titles[0] + "-" + titles[1]));
	  }
	  var shortentitle = titles[1];
	  //console.log(currentPage);
	  if (shortentitle.length > 12){
		  shortentitle = shortentitle.substring(0, 12) + "...";
	  }
	  	var prerenderFinishIcon = "<i class='loading spinner icon'></i>";
		if (preRenderComplete){
			prerenderFinishIcon = "<i class='checkmark icon' style='color: green;'></i>"
		}

	  $('#PageInfo').html("  <i class='chevron left icon' onClick='back();'></i>  <i class='setting icon' onClick='ShowSetting();'></i>" + shortentitle  + " " + prerenderFinishIcon + " " +  currentPage.toString() + "/" +  positions.length.toString() + "    " + titles[0]  +  "  ");
	  
	  //if the page reached the end, hide the auto scroll div
	  if($(window).scrollTop() + $(window).height() == $(document).height()) {
		  $('#clickInterface').hide();
	  }else if ( $('#clickInterface').is(':visible') !== true  && chapterShown !== true){
		  $('#clickInterface').show();
	  }
	});
	
	//Update Page Info (same as window.scroll function)
	function UpdatePageInfo(){
		currentPage = getPageNum($(window).scrollTop(),positions);
		if (autoSave == true && currentPage != 0){
			//Save Page number as: "title-chapter:page"
			localStorage.setItem(titles[0] + "-" + titles[1], currentPage);
		}
		//console.log(currentPage);
		var shortentitle = titles[1];
		//console.log(currentPage);
		if (shortentitle.length > 12){
			shortentitle = shortentitle.substring(0, 12) + "...";
		}

		var prerenderFinishIcon = "";
		if (preRenderComplete){
			prerenderFinishIcon = "<i class='checkmark icon'></i>"
		}

		$('#PageInfo').html("  <i class='chevron left icon' onClick='back();'></i>  <i class='setting icon' onClick='ShowSetting();'></i>" + shortentitle + " " +  prerenderFinishIcon + " " +  currentPage.toString() + "/" +  positions.length.toString() + "    " + titles[0]  + "  ");
		
	}
	
	function back(){
		window.location.href='index.html';
	}
	//Setting Interface controlling
	function ShowSetting(){
		$('#SettingInterface').fadeIn('slow');
	}
	var ExitPanel = document.getElementById('SettingInterface');
	ExitPanel.addEventListener("click", HideSetting, false);
	function HideSetting(e){
		//console.log(e.clientX);
		//console.log(e.clientY);
		pleft = $('#settingMenu').offset().left;
		pright = pleft + $('#settingMenu').width();
		ptop = $('#settingMenu').offset().top;
		pbottom = ptop + $('#settingMenu').height();
		//console.log(e.clientX,e.clientY,pleft,pright,ptop,pbottom);
		if (e.clientX < pleft || e.clientX > pright || e.clientY + $(window).scrollTop() < ptop || e.clientY + $(window).scrollTop()> pbottom){
			$('#SettingInterface').fadeOut('slow');
		}
	}
	
	//Next chapter controlling algorithm
	function NextChapter(){
		var id = nextChapterID + 1;
		if (id > maxChapterID - 1){
			
		}else{
			ChapterRedirect(chapterPaths[id]);
		}
		
		
	}
	
	function ChapterRedirect(path){
		window.location.href= "viewComic.html#" + path;
		window.location.reload();
	}
	
	
	//Show all chapters of this manga
	function ToggleChapters(){
		if (chapterShown == true){
			$('#ChapterSelector').fadeOut('slow');
			//$("html, body").animate({ scrollTop: $("#ChapterSelector").offset().top }, 1000);
			$("html, body").animate({ scrollTop: $(document).height() }, 1000);
			chapterShown = false;
			$('#clickInterface').show();
		}else{
			$('#ChapterSelector').fadeIn('slow');
			$("html, body").animate({ scrollTop: $("#ChapterSelector").offset().top }, 1000);
			//$("html, body").animate({ scrollTop: $(document).height() }, 1000);
			chapterShown = true;
			$('#clickInterface').hide();
		}
	}
	
	//Convert current view top to page number
	function getPageNum (num, arr) {
                for (var i = 0;i<arr.length;i++){
					if (arr[i] > num){
						return i;
					}
				}
				return arr.length;
            }
	
	function GoToPage(num){
		//console.log('Going to page: ' + num);
		CalculatePageOffsets();
		console.log("Going to page number:" + num);
		var targetTop = positions[num - 1];
		$('html, body').animate({scrollTop: targetTop + 5}, 1000);
	}
</script>
</body>
</html>
